package lion.dev.i18n;

import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.ResourceBundle.Control;

import org.apache.commons.lang.ArrayUtils;

/**
 * 获取i18n资源内容的方法，参考tomcat-util中的StringManager,加入了一些方便的扩展
 *
 * 如果不存在 baseName的资源文件 ，则系统默认使用packageName.strings为baseName
 *
 *
 * @author lion
 * @email hl_0074@sina.com
 * @date 2014年6月16日
 */
public class StringManager {

	private static final String BUNDLE_FILE_NAME = "strings";
	private String baseName;
	private ResourceBundle bundle;
	private Locale locale;
	private static final Map<String, Map<Locale, StringManager>> managers = new HashMap<>();

	private StringManager(String baseName, Locale locale) {

		initBundle(baseName, locale);
		if (this.bundle == null) {
			initBundle(baseName + "." + BUNDLE_FILE_NAME, locale);
		}
	}

	public static StringManager getManager(String baseName) {

		return getManager(baseName, Locale.getDefault());
	}

	public synchronized static StringManager getManager(String packageName, Locale locale) {

		Map<Locale, StringManager> map = managers.get(packageName);
		if (map == null) {
			map = new HashMap<>();
			managers.put(packageName, map);
		}
		if (locale == null) {
			locale = Locale.ENGLISH;
		}
		StringManager sm = map.get(locale);
		if (sm == null) {
			sm = new StringManager(packageName, locale);
			map.put(locale, sm);
		}
		return sm;
	}

	public Locale getLocale() {

		return this.locale;
	}

	public String getBaseName() {

		return this.baseName;
	}

	public String getString(String key) {

		return getString(key, ArrayUtils.EMPTY_OBJECT_ARRAY);
	}

	public String getString(String key, String defaultValue) {

		return getString(key, defaultValue, ArrayUtils.EMPTY_OBJECT_ARRAY);
	}

	public String getString(String key, Object[] args) {

		return getString(key, key, args);
	}

	public String getString(String key, String defaultValue, Object[] args) {

		String result = null;
		if (this.bundle != null) {
			result = this.bundle.getString(key);
		}
		if (result == null) {
			result = key;
		} else if (args != null && args.length > 0) {
			result = MessageFormat.format(result, args);
		}

		return result;
	}

	private void initBundle(String baseName, Locale locale) {

		ResourceBundle bundle = null;
		try {
			bundle = ResourceBundle.getBundle(baseName, locale, Control.getNoFallbackControl(Control.FORMAT_PROPERTIES));
		} catch (Exception e) {
			return;
		}
		this.baseName = baseName;
		this.bundle = bundle;
		this.locale = bundle.getLocale();
	}
}
